<template>
	<view style="height: 110rpx;"></view>
	<view class="movable-area">
		<view class="movable-view" direction="all" style=" margin-bottom: 10rpx; text-align: center;padding-top: 30rpx;font-size: 40rpx;font-weight: bold;">
			垃圾分类
		</view>
	</view>
	<view class="content">
		<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" circular="true"
			style="width: 95vw;height: 400rpx;">
			<swiper-item v-for="(item,index) in SwiperImg" :key="index">
				<view class="swiper-item">
					<image :src="item.imgSrc" mode="aspectFill"></image>
				</view>
			</swiper-item>
		</swiper>

		<!-- 搜索模块 -->
		<view class="Search">
			<image src="../../static/search.png"></image>
			<input type="text" placeholder="请输入你要查询的垃圾" v-model="InputVal" @confirm="GetInputVal"
				style="flex-grow: 11;">
			<image src="../../static/camera.png" mode="" @click="GetImg"></image>
		</view>
		<!-- 分类列表模块 -->
		<view class="Category">
			<view class="CategoryItem" v-for="(item,index) in CategoryImg" :key="index" @click="NavTo(index)">
				<image :src="item.CateImgSrc" ></image>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, reactive, ref } from 'vue'
	import { pathToBase64, base64ToPath } from '../../js_sdk/mmmm-image-tools/index.js'

	interface SwiperImage {
		imgSrc : string;
	}

	interface TypeListItem {
		name : string;
		imgSrc : string;
		type : string;
	}

	interface WasteInfo {
		title : string;
		content : string;
		imgSrc : string;
		typeList : TypeListItem[];
	}

	interface CategoryImage {
		CateImgSrc : string;
		Navto : string;
		'background-color' : string;
		wasteInfo : WasteInfo;
	}

	const SwiperImg = reactive<SwiperImage[]>([
		{ imgSrc: "/static/Fig1.png" },
		{ imgSrc: "/static/Fig2.png" },
		{ imgSrc: "/static/Fig3.png" }
	]);

	const CategoryImg = reactive<CategoryImage[]>([
		{
			'CateImgSrc': "/static/RecyclableWaste.png",
			"Navto": "/pages/WasteInfo/WasteInfo",
			"background-color": "rgb(58,123,176)",
			"wasteInfo": {
				"title": "可回收垃圾",
				"content": "可回收垃圾就是可以再生循环的垃圾。本身或材质可再利用的纸类、硬纸板、玻璃、塑料、金属、塑料包装，与这些材质有关的如:报纸、杂志、广告单及其它干净的纸类等皆可回收。另外包装上有绿色标章是属于要付费的双系统，亦属于可回收垃圾。",
				"imgSrc": "/static/recyclable.png",
				"typeList": [
					{ "name": '电子产品类', "imgSrc": "/static/recyclable/electr.png", "type": "electronics" },
					{ "name": '废品玻璃类', "imgSrc": "/static/recyclable/glass.png", "type": "glass" },
					{ "name": '金属类', "imgSrc": "/static/recyclable/metals.png", "type": "metals" },
					{ "name": '废纸类', "imgSrc": "/static/recyclable/paper.png", "type": "paper" },
					{ "name": '塑料制品类', "imgSrc": "/static/recyclable/plastics.png", "type": "plastics" },
					{ "name": '纺织物类', "imgSrc": "/static/recyclable/textile.png", "type": "textile" }
				]
			}
		},
		{
			'CateImgSrc': "/static/hazardousWaste.png",
			"Navto": "/pages/WasteInfo/WasteInfo",
			"background-color": "rgb(196,75,58)",
			"wasteInfo": {
				"title": "有害垃圾",
				"content": "有害垃圾，指生活垃圾中对人体健康或自然环境造成直接或潜在危害的物质，必须单独收集、运输、存贮，由环保部门认可的专业机构进行特殊安全处理。常见的有害垃圾包括废灯管、废油漆、杀虫剂、废弃化妆品、过期药品、废电池、废灯泡、废水银温度计等，有害垃圾需按照特殊正确的方法安全处理。",
				"imgSrc": "/static/hazardous.png",
				"typeList": [
					{ "name": '灯泡', "imgSrc": "/static/hazardous/bulb.png", "type": "bulb" },
					{ "name": '废弃电池', "imgSrc": "/static/hazardous/cell.png", "type": "battery" },
					{ "name": '生活类', "imgSrc": "/static/hazardous/drug.png", "type": "household" },
					{ "name": '油漆类', "imgSrc": "/static/hazardous/paint.png", "type": "paint" }
				]
			}
		},
		{
			'CateImgSrc': "/static/kitchenWaste.png",
			"Navto": "/pages/WasteInfo/WasteInfo",
			"background-color": "rgb(32,145,76)",
			"wasteInfo": {
				"title": "厨余垃圾",
				"content": "厨余垃圾是指居民日常生活及食品加工、饮食服务、单位供餐等活动中产生的垃圾，包括丢弃不用的菜叶、剩菜、剩饭、果皮、蛋壳、茶渣、骨头等，其主要来源为家庭厨房、餐厅、饭店、食堂、市场及其他与食品加工有关的行业。",
				"imgSrc": "/static/kitchen.png",
				"typeList": [
					{ "name": '骨头类', "imgSrc": "/static/kitchen/bone.png", "type": "bone" },
					{ "name": '厨余垃圾', "imgSrc": "/static/kitchen/leftovers.png", "type": "kitchen" },
					{ "name": '其他类', "imgSrc": "/static/kitchen/other.png", "type": "other" },
					{ "name": '蔬菜果皮', "imgSrc": "/static/kitchen/peel.png", "type": "vegetable" }
				]
			}
		},
		{
			'CateImgSrc': "/static/residualWaste.png",
			"Navto": "/pages/WasteInfo/WasteInfo",
			"background-color": "rgb(82,82,82)",
			"wasteInfo": {
				"title": "其他垃圾",
				"content": "其他垃圾，指除可回收物、有害垃圾、餐厨垃圾外的其他生活垃圾，即现环卫体系主要收集和处理的垃圾，一般都采取填埋、焚烧等方法处理，部分还可以使用生物分解的方法解决，如放蚯蚓等。其他垃圾是可回收物、厨余垃圾、有害垃圾剩余下来的一种垃圾种类。",
				"imgSrc": "/static/residual.png",
				"typeList": [
					{ "name": '无法再生用品', "imgSrc": "/static/residual/CannotRecycleSupplies.png", "type": "non-recyclable" },
					{ "name": '灰土陶瓷', "imgSrc": "/static/residual/ceramics.png", "type": "ceramics" },
					{ "name": '一次性餐具', "imgSrc": "/static/residual/DisposableTableware.png", "type": "disposable" },
					{ "name": '其他类', "imgSrc": "/static/residual/other.png", "type": "misc" }
				]
			}
		}
	]);

	const InputVal = ref('');

	function NavTo(index : number) {
		let newURL = CategoryImg[index].Navto + "?index=" + index + "&background-color=" + CategoryImg[index]['background-color'] + "&title=" + CategoryImg[index].wasteInfo.title;
		console.log(newURL);
		uni.navigateTo({
			url: newURL,
			success: (res) => {
				res.eventChannel.emit("WasteInfoFunc", { data: CategoryImg[index].wasteInfo });
			}
		});
	}
	onMounted(()=>{
		uni.showModal({
			title:"请选择浏览的模式",
			success:function(res){
				if (res.confirm){
					uni.redirectTo({
						url:"/pages/index2/index2"
					})
				}else if (res.cancel){
				}
			},
			confirmText:"关怀模式",
			cancelText:"正常浏览"
		})
	})
	function GetImg() {
		uni.chooseImage({
			count: 1,
			success(res) {
				console.log(res.tempFilePaths);
				uni.showLoading({
					title: "努力识别中......"
				});
				let path = res.tempFilePaths[0];
				pathToBase64(path).then(base64 => {
					console.log(base64);
					uni.request({
						url: 'https://apis.tianapi.com/imglajifenlei/index',
						method: "POST",
						header: {
							"Content-Type": "application/x-www-form-urlencoded"
						},
						data: {
							key: "afa0f8783581e69ab6434a8a10d46f43",
							img: base64
						},
						success: (res) => {
							console.log(res);
							uni.hideLoading();
							uni.showModal({
								title: "识别结果",
								content: res.data.result.list[0].lajitip
							});
						},
						fail: (err) => {
							console.error(err);
							uni.hideLoading();
							uni.showToast({
								title: '识别失败，请重试',
								icon: 'none'
							});
						}
					});
				})
					.catch(error => {
						console.log(error);
						uni.hideLoading();
						uni.showToast({
							title: '图片处理失败',
							icon: 'none'
						});
					});
			}
		});
	}

	function GetInputVal() {
		if (!InputVal.value) {
			uni.showToast({
				title: '请输入搜索内容',
				icon: 'none'
			});
			return;
		}

		console.log("开始搜索:", InputVal.value);
		uni.showLoading({
			title: "搜索中..."
		});

		uni.request({
			url: "https://apis.tianapi.com/lajifenlei/index",
			method: "POST",
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"Accept": "application/json"
			},
			data: {
				key: "afa0f8783581e69ab6434a8a10d46f43",
				word: InputVal.value
			},
			success: (res) => {
				console.log("API响应:", res);
				uni.hideLoading();
				if (res.statusCode === 200 && res.data && res.data.code === 200 && res.data.result && res.data.result.list && res.data.result.list.length > 0) {
					uni.showModal({
						title: "搜索结果",
						content: `物品: ${res.data.result.list[0].name}\n分类: ${CategoryImg[res.data.result.list[0].type].wasteInfo.title}\n解释: ${res.data.result.list[0].explain || '暂无解释'}`
					});
				} else {
					uni.showToast({
						title: '未找到相关信息',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				console.error("请求失败:", err);
				uni.hideLoading();
				uni.showToast({
					title: '搜索失败，请检查网络',
					icon: 'none',
					duration: 2000
				});
			}
		});
	}

	function startVoiceRecognition() {
		uni.showToast({
			title: '开始语音识别',
			icon: 'none',
			duration: 1000
		});

		const recorderManager = uni.getRecorderManager();

		recorderManager.onStart(() => {
			console.log('录音开始');
		});

		recorderManager.onStop((res) => {
			console.log('录音结束', res);
			const { tempFilePath } = res;

			// 读取录音文件并转换为 base64
			plus.io.resolveLocalFileSystemURL(tempFilePath, (entry) => {
				entry.file((file) => {
					const reader = new plus.io.FileReader();
					reader.onloadend = function (e) {
						const base64Audio = e.target.result.split(',')[1];
						sendVoiceToAPI(base64Audio);
					}
					reader.readAsDataURL(file);
				});
			});
		});

		const options = {
			duration: 10000,
			sampleRate: 16000,
			numberOfChannels: 1,
			encodeBitRate: 96000,
			format: 'wav',
			frameSize: 50
		}

		recorderManager.start(options);

		// 10秒后自动停止录音
		setTimeout(() => {
			recorderManager.stop();
		}, 10000);
	}

	function sendVoiceToAPI(base64Audio : string) {
		uni.showLoading({
			title: '正在识别...'
		});

		uni.request({
			url: 'https://apis.tianapi.com/voicelajifenlei/index',
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			data: {
				key: 'afa0f8783581e69ab6434a8a10d46f43',
				say: base64Audio,
				format: 'wav'
			},
			success: (res) => {
				uni.hideLoading();
				if (res.data.code === 200 && res.data.result) {
					InputVal.value = res.data.result.list[0].name;
					GetInputVal(); // 自动搜索识别结果
				} else {
					uni.showToast({
						title: '语音识别失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				console.error('语音识别请求失败:', err);
				uni.hideLoading();
				uni.showToast({
					title: '语音识别失败，请重试',
					icon: 'none'
				});
			}
		});
	}
	
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-image: url("../../static/R-C (1).jpg");
		background-size: 100%;
		height: 100%;
	}
	.swiper-item image{
		width: 100%;
		height: 400rpx;

	}
	.Category{
		/* border: 1px solid salmon; */
		width: 95vw;
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		margin-top: 10rpx;

	}
	.CategoryItem image{
		width: 300rpx;
		height: 500rpx;
		
	}
	.CategoryItem{
		margin: 10rpx 20rpx;
		box-shadow: 1.5rpx 1.5rpx 6rpx 6rpx silver;
/* 		display: flex; */
/* 		flex-direction: column;
		align-items: center; */
		width: 300rpx;
		height: 500rpx;		
	}
/* 	.CategoryItem2{
		margin: 5rpx 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 130rpx;
		height: 140rpx;		
	} */
/* 	.CategoryItem2 image{
		width: 90rpx;
		height: 160rpx;
		
	} */
	.Search {
	/* 		border: solid; */
			display: flex;
			border-radius: 20rpx;
			height: 80rpx;
			align-items: center;
			margin: 30rpx;
			background-color: white;
			width: 70%;
			
		}
	
		.Search image {
			height: 50rpx;
			width: 50rpx;
			margin: 0 5px;
		}

		.headline{
			background-image: url("../../static/R-C (1).jpg");
		}
		  .movable-area{
		    pointer-events:none;
		    z-index: 100;
		    width: 100%;
		    height: 100%;
		    position: fixed;
		    top: 0;
		    left: 0;
		    right: 0;
		    bottom: 0;
		  }
		  .movable-view{ 
		  	pointer-events:auto;
		    height: 80rpx;
		    width: 100%;
		    background-image: url("../../static/R-C (1).jpg");
		  }

</style>